package partParsers;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import util.HtmlTextFinder;

//this class extracts indexes of advertisments from real estate html
public class IndexesFinder implements PartParser {
	protected int[] indexes=null;//list of advertisment indexes of site
	protected String idToken=null;
	protected String tablePrefix=null;//html text that preceeds data table
	protected Set<String> arr=new HashSet<String>();
	protected HtmlTextFinder txtFinder;
	
	public IndexesFinder(String buf,String idToken,String tablePrefix) {
		txtFinder=new HtmlTextFinder(buf);
		this.tablePrefix=tablePrefix;
		this.idToken=idToken;
	}
	
	//returns type of i'th column in main advertisment's table
	public int getMember(int i){return indexes[i];}
	
	//returns number of columns in main advertisment's table
	public int getRowNumber(){return indexes.length;}
	
	//read all indexes of advertisments from site
	//initializes 'buffer' and 'indexes' attributes
	public boolean parse()
		throws IOException
	{
		//Copy every table with title data (have idToken) to
		int pos,startPos;//position of last data id token found
		String id;//index of last data token found
						
		int len=txtFinder.getBufLen();
		
		//look for prefix of advertisment table
		pos=txtFinder.indexOf(tablePrefix);
		if(pos<0)
			pos=0;		
		
		//look for indexes of advertisments
		while(pos>=0 && pos<len)
		{
			pos=txtFinder.indexOf(idToken,pos);
			if(pos==-1)
				break;
			pos+=idToken.length();
			startPos=pos;
			
			//find current advertisment data index												
			for(;pos<len && Character.isDigit(txtFinder.charAt(pos));pos++);
			id=txtFinder.substring(startPos,pos);
			try{
				Integer.parseInt(id);
				arr.add(id);
			}
			catch(NumberFormatException e){}
		}
			
		if(arr.size()==0)
			return false;
		
		indexes=new int[arr.size()];
		Iterator it=arr.iterator();		
		for(pos=0;pos<arr.size();pos++)
			indexes[pos]=Integer.parseInt((String)it.next());
		
		return true;
	}

	public Object[] toArray() {
		return arr.toArray();
	}

	public String getData(int i, int j) {
		return String.valueOf(indexes[i]);
	}

}
